package com.platform.controller;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.platform.base.PageUtil;
import com.platform.base.R;
import com.platform.base.mvc.BaseController;
import com.platform.dto.Modular;
import com.platform.logger.annotation.ApiLog;
import com.platform.service.IModular;
import com.platform.utils.StringUtils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


/**
 * 
 * <p> Title:Mkxx Mapper</p>
 * <p> desc:  模块信息</p>
 * <p> Copyright: Copyright (c) 2019 </p>
 * <p> Company: </p>
 * 
 * @author wys
 * @version 1.0
 */
@Controller
@RequestMapping("modular") 
@Api(tags="OMS-菜单资源模块")
public class ModularController extends BaseController{
	
	@Autowired
    private IModular services;
    
    @RequestMapping(value="data",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="分页查询")
    public Object selectAll(Modular dto,Integer start,Integer limit,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
        PageUtil pageUt = new PageUtil();
        pageUt.setPageIndex(start);
        pageUt.setPageSize(limit);
    	pageUt.setParams(BeanUtil.beanToMap(dto));
        List<Modular> servicesList = services.selectByPaging(pageUt);
        return R.success(servicesList, pageUt.getTotal());
    }
    
    @RequestMapping(value="dataAll",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="获取所有数据")
    public Object select(Modular dto,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
        List<Modular> servicesList = services.selectAll(BeanUtil.beanToMap(dto));
        return R.success(servicesList);
    }
    
    @ApiLog(value="菜单资源删除",desc="系统菜单资源删除")
    @SuppressWarnings("all")
    @RequestMapping(value="delete",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="删除数据")
    public Object delete(String ids) throws IOException {
    	boolean isSuccess = false;
    	String fieldMsg = "";
    	String[] removes = ids.split(",");
    	for(int i=0;i<removes.length;i++){
    		Modular modular = services.get(removes[i]);
    		if(services.selectMKByParent(modular.getModularcode()).isEmpty()) {
    			isSuccess = services.delete(modular);
    		}else {
    			isSuccess = false;
    			fieldMsg = modular.getName()+"包含子集不能删除";
    		}
    	}
    	if(isSuccess){
    		return R.success();
    	}else {
    		return R.fail(fieldMsg);
    	}
    }
    
    @ApiLog(value="菜单资源新增",desc="系统菜单资源新增")
    @RequestMapping(value="save",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="新增数据")
    public Object insert(@Valid Modular dto,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
    	if(!StringUtils.isEmpty(dto.getModularright())){
    		dto.setModularright(dto.getModularright().replace("[","").replace("]", "").replaceAll("\"",""));
    	}
        dto.setCreateDate(new Date());
        dto.setCreater(getName());
    	if(services.insert(dto)){
    		return R.success();
    	}else{
    		return R.fail();
    	}
    }
    
    @ApiLog(value="菜单资源编辑",desc="系统菜单资源编辑")
    @RequestMapping(value="edit",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="修改数据")
    public Object update(@Valid Modular dto) {
    	dto.setLastModifyDate(new Date());
    	dto.setLastModifier(getName());
    	if(services.update(dto)){
        	return R.success();
    	}else{
    		return R.fail();
    	}
    }
    
    @RequestMapping(value="find",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="获取单条数据")
    public Object get(String code, HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
        return services.get(code);
    }
    
    @RequestMapping(value="selectTreeByParent",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="查询父节点")
    public Object selectTreeByParent(HttpServletRequest request, HttpServletResponse response) {
        return services.selectParent();
    }
    
    @RequestMapping(value="selectTreeByFlID",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="根据父节点查询子节点")
    public Object selectTreeByFlID(String fl, HttpServletRequest request, HttpServletResponse response) {
        return services.selectMKByParent(fl);
    }

    @RequestMapping(value="modularTree",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="获取资源树")
    public Object treeModular(String parentCode){
    	List<Modular> modularList = null;
    	Map<String,Object> searchMap = MapUtil.newHashMap();
    	searchMap.put("parent_", StringUtils.isEmpty(parentCode)?"0":parentCode);
    	modularList = services.selectAll(searchMap);
    	modularListBuild(modularList);
    	return modularList;
    }
	
    private void modularListBuild(List<Modular> modulars){
    	List<Modular> modularList = new ArrayList<Modular>();
    	for(Modular m : modulars){
    		Map<String,Object> childrenMap = MapUtil.newHashMap();
    		childrenMap.put("parent_", m.getModularcode());
    		List<Modular> childrenList = services.selectAll(childrenMap);
    		if(childrenList != null && childrenList.size() > 0){
    			modularListBuild(childrenList);
    		}else{
    			m.setLeaf(true);
    			if(m.getParent_().equals("0")){
    				modularList.add(m);
    			}
    			continue;
    		}
    		m.setChildren(childrenList);
    	}
    }
    
    @RequestMapping(value="roleAuthorization",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="查询指定节点下的子节点")
    public Object roleAuthorization(String parentCode){
    	List<Modular> modularList = null;
    	Map<String,Object> searchMap = MapUtil.newHashMap();
    	searchMap.put("parent_", StringUtils.isEmpty(parentCode)?"0":parentCode);
    	modularList = services.selectAll(searchMap);
    	modularListBuildRight(modularList);
    	return modularList;
    }
    
    private void modularListBuildRight(List<Modular> modulars){
    	List<Modular> modularList = new ArrayList<Modular>();
    	for(Modular m : modulars){
    		Map<String,Object> childrenMap = MapUtil.newHashMap();
    		childrenMap.put("parent_", m.getModularcode());
    		List<Modular> childrenList = services.selectAll(childrenMap);
    		if(childrenList != null && childrenList.size() > 0){
    			modularListBuild(childrenList);
    		}else{
    			m.setLeaf(true);
    			if(m.getParent_().equals("0")){
    				modularList.add(m);
    			}
    			continue;
    		}
    		m.setChildren(childrenList);
    	}
    	modulars.removeAll(modularList);
    }
}
